package args

import (
	"errors"
	"flag"
	"fmt"
	"gitee-lfs-multipart-transfer/internal/color"
	"gitee-lfs-multipart-transfer/internal/common"

	"os"
)

type Args struct {
	help               bool
	version            bool
	LfsEnableMultipart string
	LfsMultipartUpload bool
}

func NewArgs() (*Args, error) {
	if len(os.Args) < 2 {
		return nil, errors.New("at least one argument is required")
	}

	arg := &Args{}

	flag.BoolVar(&arg.help, "h", false, "show help")
	flag.BoolVar(&arg.help, "help", false, "show help")

	flag.BoolVar(&arg.version, "v", false, "show version")
	flag.BoolVar(&arg.version, "version", false, "show version")

	flag.StringVar(&arg.LfsEnableMultipart, "lfs-enable-multipart", "", "repo path to enable multipart transfer")
	flag.BoolVar(&arg.LfsMultipartUpload, "lfs-multipart-upload", false, "enable multipart transfer")

	flag.Usage = arg.Usage
	flag.Parse()
	arg.invoke()

	return arg, nil
}

func (a *Args) Usage() {
	fmt.Fprintf(os.Stderr, `multipart-transfer - transfer large lfs objects to gitee in multiple parts
Usage: %s [option] [repo-path]
 --lfs-enable-multipart <repo-path>  set up repo to enable transfer
 -v | --version  Version message
 -h | --help     Usage message
`, os.Args[0])
}

func (a *Args) Version() {
	fmt.Fprintf(os.Stderr, `version:      %s
build time:   %s
build commit: %s
go version:   %s
`,
		color.Yellow(common.Version),
		color.Yellow(common.BuildTime),
		color.Yellow(common.BuildCommit),
		color.Yellow(common.BuildGoVersion),
	)
}

func (a *Args) invoke() {
	if a.help {
		flag.Usage()
		os.Exit(0)
	}

	if a.version {
		a.Version()
		os.Exit(0)
	}
}
